﻿using Modbus.Device;
using ProductMonitor.Models;
using ProductMonitor.UserControls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Threading;

namespace ProductMonitor.ViewModels
{
    class MainWindowVM : INotifyPropertyChanged
    {
        /// <summary>
        /// 通知接口
        /// </summary>
        public event PropertyChangedEventHandler? PropertyChanged;

        //声明一个计时器--用于更新系统时间
        private readonly System.Timers.Timer timer;

        public MainWindowVM()
        {
            // 初始化计时器，每秒触发一次(只读字段只能在创建时候初始化或者在类的构造函数中初始化)
            timer = new System.Timers.Timer(1000);
            timer.Elapsed += UpdateDateTime;
            timer.Start();

            #region 初始化环境配置信息

            Task.Run(new Action(() =>
            {
                while (true)
                {
                    //创建串口
                    using (SerialPort serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One))
                    {
                        serialPort.Open();

                        //里氏替换原则，ModbusSerialMaster继承自IModbusMaster
                        IModbusMaster master = ModbusSerialMaster.CreateRtu(serialPort);
                        var listValue = master.ReadHoldingRegisters(1, 0, 7);

                        EnvironmentList = new List<EnvironmentModel>();

                        //赋值
                        for (int i = 0; i < listValue.Count(); i++)
                        {
                            EnvironmentList.Add(new EnvironmentModel 
                            {
                                EnvItemName = environmentNameList[i],
                                EnvItemValue = listValue[i]
                            });
                        }
                    }
                }
            }));

            #endregion

            #region 初始化报警信息
            AlarmList = new List<AlarmModel>
            {
                new AlarmModel{ AlarmNum="01",AlarmMsg="设备温度过高", AlarmTime="2024-12-18 10:19:555", AlarmDuration=50 },
                new AlarmModel{ AlarmNum="02",AlarmMsg="车间温度过高", AlarmTime="2024-12-12 10:19:555", AlarmDuration=30 },
                new AlarmModel{ AlarmNum="03",AlarmMsg="设备转速过快", AlarmTime="2024-12-11 10:19:555", AlarmDuration=55 },
                new AlarmModel{ AlarmNum="04",AlarmMsg="设备气压过高", AlarmTime="2024-12-10 10:19:555", AlarmDuration=23 },
                new AlarmModel{ AlarmNum="05",AlarmMsg="设备电压过高", AlarmTime="2024-11-18 10:19:555", AlarmDuration=11 },
            };
            #endregion

            #region 初始化设备信息

            DeviceList = new List<DeviceModel>
        {
            new DeviceModel{DevItemName="电能(Kw.h)",DevItemValue=60.8 },
            new DeviceModel{DevItemName="电流(A)",DevItemValue=5},
            new DeviceModel{DevItemName="电压(V)",DevItemValue=390 },
            new DeviceModel{DevItemName="压差(Kpa)",DevItemValue=13 },
            new DeviceModel{DevItemName="温度(°C)",DevItemValue=36 },
            new DeviceModel{DevItemName="震动(mm/s)",DevItemValue = 4.1},
            new DeviceModel{DevItemName="转速(r/min)",DevItemValue=2600 },
            new DeviceModel{DevItemName="气压(Kpa)",DevItemValue=0.5 },
        };

            #endregion

            #region 初始化雷达图信息

            RadarList = new List<RadarModel>
        {
            new RadarModel{ItemName="排烟风机",Value=90 },
            new RadarModel{ItemName="客梯",Value=30 },
            new RadarModel{ItemName="供水机",Value=34.89 },
            new RadarModel{ItemName="喷淋水泵",Value=69.59 },
            new RadarModel{ItemName="稳压设备",Value=20 },
        };

            #endregion

            #region 初始化人力资源数据

            StaffAbsencesList = new List<StaffAbsenceModel>
        {
            new StaffAbsenceModel{Name="张三三",Department="技术部",AbsenceCount=130 },
            new StaffAbsenceModel{Name="李四",Department="行政部",AbsenceCount=60 },
            new StaffAbsenceModel{Name="王五",Department="财务部",AbsenceCount=20 },
            new StaffAbsenceModel{Name="赵六",Department="销售部",AbsenceCount=120 },
            new StaffAbsenceModel{Name="钱七七",Department="技术部",AbsenceCount=30 },
        };
            #endregion

            #region 初始化车间信息
            WorkShopList = new List<WorkShopModel>
        {
            new WorkShopModel{WorkShopName="贴片车间",WorkingCount=32,WaitingCount=8,BrokenCount=4,StopCount=0 },
            new WorkShopModel{WorkShopName="封装车间",WorkingCount=40,WaitingCount=6,BrokenCount=4,StopCount=1 },
            new WorkShopModel{WorkShopName="焊接车间",WorkingCount=36,WaitingCount=8,BrokenCount=4,StopCount=0 },
            new WorkShopModel{WorkShopName="组装车间",WorkingCount=15,WaitingCount=2,BrokenCount=2,StopCount=0 },
        };
            #endregion

            #region 初始化机台信息

            MachineLsit = new List<MachineModel>();

            //随机生成数据
            Random random = new Random();
            for (int i = 0; i < 20; i++)
            {
                int plan = random.Next(100, 1000);//计划机台数量
                int finshed = random.Next(100, plan);//实际完成数量

                int statusNum = random.Next(0, 2);//必须到2，因为不包含右区间

                MachineLsit.Add(new MachineModel
                {
                    Name = "焊接机-" + (i + 1),
                    Status = statusNum == 1 ? "作业中" : "停止中",
                    StatusColor = (statusNum == 1 ? "LightGreen" : "Red"),
                    PlanCount = plan,
                    FinshedCount = finshed,
                    OrderNO = "H20250105" + i,
                });
            }



            #endregion
        }


        #region 所有的事件

        //更新时间事件
        private void UpdateDateTime(object sender, ElapsedEventArgs e)
        {
            var now = DateTime.Now;
            Application.Current.Dispatcher.BeginInvoke(new Action(() =>
            {
                Time = now.ToString("HH:mm:ss");
                Date = now.ToString("yyyy:MM:dd");
                WeekDay = now.ToString("dddd");
            }));
        }

        #endregion

        #region 所有的属性

        #region 用户控件绑定
        /// <summary>
        /// 监控的用户控件
        /// </summary>
        private UserControl childUC;

        /// <summary>
        /// 监控用户控件属性
        /// </summary>
        public UserControl ChildUC
        {
            get
            {
                if (childUC == null)
                {
                    childUC = new MonitorUC();//里氏替换原则
                }
                return childUC;
            }
            set
            {
                childUC = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("ChildUC"));
            }
        }
        #endregion

        #region 时间属性信息
        private string time = string.Empty;

        public string Time
        {
            get => time;
            set
            {
                if (time != value)
                {
                    time = value;
                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Time"));
                }
            }
        }

        private string date = string.Empty;
        public string Date
        {
            get => date;
            set
            {
                if (date != value)
                {
                    date = value;
                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Date"));
                }
            }
        }

        private string weekDay = string.Empty;
        public string WeekDay
        {
            get => weekDay;
            set
            {
                if (weekDay != value)
                {
                    weekDay = value;
                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("WeekDay"));
                }
            }
        }
        #endregion

        //#region 时间信息
        ///// <summary>
        ///// 时间: 时分
        ///// </summary>
        //public string StrTime
        //{
        //    get
        //    {
        //        return DateTime.Now.ToString("HH:mm");
        //    }
        //}

        ///// <summary>
        ///// 年月日
        ///// </summary>
        //public string StrDate
        //{
        //    get
        //    {
        //        return DateTime.Now.ToString("yy-MM-dd");
        //    }
        //}

        ///// <summary>
        ///// 星期
        ///// </summary>
        //public string StrWeeks
        //{
        //    get
        //    {
        //        int index = (int)DateTime.Now.DayOfWeek;
        //        string[] weeks = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", };
        //        return weeks[index];
        //    }
        //}
        //#endregion

        #region 生产机台信息
        /// <summary>
        /// 机台总数
        /// </summary>
        private string machineCount = "0298";

        public string MachineCount
        {
            get
            {
                return machineCount;
            }
            set
            {
                machineCount = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("MachineCount"));
            }
        }



        /// <summary>
        /// 生产产品总数
        /// </summary>
        private string productCount = "0198";

        public string ProductCount
        {
            get
            {
                return productCount;
            }
            set
            {
                productCount = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("ProductCount"));
            }
        }

        /// <summary>
        /// 不良产品总数
        /// </summary>
        private string badCount = "0098";

        public string BadCount
        {
            get
            {
                return badCount;
            }
            set
            {
                badCount = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("BadCount"));
            }
        }
        #endregion

        #region 环境项信息

        /// <summary>
        /// 环境项集合
        /// </summary>
        private readonly List<string> environmentNameList=new List<string>
                                    { "光照(Lux)", "噪音(db)","温度(°C)","湿度(%)","PM2.5(m³)","硫化氢(PPM)","氮气(PPM)"};

        private List<EnvironmentModel> environmentList;

        public List<EnvironmentModel> EnvironmentList
        {
            get
            {
                return environmentList;
            }
            set
            {
                environmentList = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("EnvironmentList"));
            }
        }


        #endregion

        #region 报警信息

        /// <summary>
        /// 报警信息集合
        /// </summary>

        private List<AlarmModel> alarmList;

        public List<AlarmModel> AlarmList
        {
            get
            {
                return alarmList;
            }
            set
            {
                alarmList = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("AlarmList"));
            }
        }


        #endregion

        #region 设备信息
        private List<DeviceModel> deviceList;

        public List<DeviceModel> DeviceList
        {
            get
            {
                return deviceList;
            }
            set
            {
                deviceList = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("DeviceList"));
            }
        }

        #endregion

        #region 雷达图数据

        private List<RadarModel> radarList;

        public List<RadarModel> RadarList
        {
            get
            {
                return radarList;
            }
            set
            {
                radarList = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("RadarList"));
            }
        }

        #endregion

        #region 人力资源相关

        private List<StaffAbsenceModel> staffAbsenceList;

        public List<StaffAbsenceModel> StaffAbsencesList
        {
            get { return staffAbsenceList; }
            set
            {
                staffAbsenceList = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("StaffAbsencesList"));
            }
        }


        #endregion

        #region 车间信息

        private List<WorkShopModel> workShopList;

        public List<WorkShopModel> WorkShopList
        {
            get { return workShopList; }
            set
            {
                workShopList = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("WorkShopList"));
            }
        }

        #endregion

        #region 机台工作状态信息


        private List<MachineModel> machineLsit;

        public List<MachineModel> MachineLsit
        {
            get { return machineLsit; }
            set
            {
                machineLsit = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("MachineLsit"));
            }
        }

        #endregion

        #endregion
    }
}
